<template>
  <a-modal
    :title="title"
    :width="600"
    :height="900"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top: 5%; height: 700"
  >
    <!-- table区域-begin -->
    <a-row>
      <!-- <a-col a-col :xs="24" :sm="16"> </a-col> -->
      <a-col a-col :xs="24" :sm="12">
        <a-input ref="inputName" v-model="inputSN" @keyup.enter="insertSN"></a-input>
      </a-col>
      <a-col a-col :xs="24" :sm="6">
        <a-button type="primary" icon="plus" @click="newSubData">新增序列号</a-button>
      </a-col>
      <!-- <a-button type="primary" icon="plus" @click="importSN" v-if="inventorytype === '1'">引入序列号</a-button> -->
      <a-col a-col :xs="24" :sm="6">
        <a-button type="primary" @click="deletSubData">删除行</a-button>
      </a-col>
    </a-row>
    <a-row>
      <a-col :xs="24" :sm="24">
        <el-table
          ref="table"
          :data="snDataSource"
          border
          style="width: 100%"
          @cell-dblclick="tableDbEdit"
          @row-click="onRowClick"
        >
          <el-table-column type="index" width="50"> </el-table-column>
          <el-table-column prop="sncode" label="序列号" v-if="inventorytype === '0'">
            <template slot-scope="scope">
              <!-- 条件判断如果满足则显示表单，否则默认展示文字 -->
              <el-input
                size="middle"
                v-model="scope.row.sncode"
                @blur="blurInput(scope.row.id, 'sncode', scope.row.sncode)"
              >
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="sncode" label="序列号" v-if="inventorytype === '1'">
            <template slot-scope="scope">
              <el-select
                size="middle"
                @focus="getSnCodeList()"
                @click="getSnCodeList()"
                @blur="blurInput(scope.row.id, 'sncode', scope.row.sncode)"
                v-model="scope.row.sncode"
                clearable
                placeholder="请选择"
              >
                <el-option v-for="item in instocksnlist" :key="item.id" :label="item.sncode" :value="item.sncode">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { randomUUID } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '../../../../api/manage'
export default {
  name: 'InventorySn',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      title: '操作',
      visible: false,
      loading: false,
      inputSN: '',
      disableMixinCreated: true,
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectBillRows: [],
      selectBillDetailRows: [],
      showType: 'basic',
      selectType: 'list',
      linkNumber: '',
      organId: '',
      companyid: '',
      warehouseid: '',
      inventorytype: '', //库存类型，0入库，1出库
      discount: '',
      deposit: '',
      remark: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 表头
      columns: [
        {
          title: '物料编号',
          dataIndex: 'materialcode',
          width: 200
        },
        {
          title: '物料名称',
          dataIndex: 'materialname',
          width: 200
        },
        {
          title: '物料数量',
          dataIndex: 'qty',
          width: 200
        }
      ],
      dataSource: [],
      snColumns: [
        {
          title: '序列号',
          key: 'sncode',
          width: 150
        },
        {
          title: ''
        }
      ],
      snDataSource: [],
      url: {
        // list: '/so/scmdelivery/getreferlist'
        getsnlist: '/inventory/scminventoy/getsncode',
        getinstocksnlist: '/base/scmsn/getinstocksnlist'
      },
      showInput: '',
      oldData: {},
      instocksnlist: [],
      parentid: '',
      materialid: '',
      qty: '',
      selectRowId: ''
    }
  },
  computed: {
    getType: function() {
      return 'radio'
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.$refs.inputName.focus()
    })
  },
  methods: {
    async insertSN() {
      if (this.inventorytype === '0') {
        //入库的时候需要扫描入库，所以需要手工录入序列号
        console.log('insert sn:' + this.inputSN)
        //自动增加到下面的序列号里
        const newData = {
          id: randomUUID(),
          materialid: '',
          sncode: this.inputSN,
          parentid: this.parentid
        }
        this.snDataSource = [...this.snDataSource, newData]

        this.inputSN = ''
      } else if (this.inventorytype === '1') {
        //如果是出库序列，则自动从当前序列号档案中选择扫码出来的序列号
        let inputSnCode = this.inputSN
        let params = {
          materialid: this.materialid,
          companyid: this.companyid,
          warehouseid: this.warehouseid,
          sncode: inputSnCode
        }
        let snret = await getAction(this.url.getinstocksnlist, params)
        if (snret) {
          if (snret.success) {
            let newData = {
              id: snret.result[0].id,
              materialid: '',
              sncode: inputSnCode,
              parentid: this.parentid
            }
            // this.snDataSource = [...this.snDataSource, newData]
            this.snDataSource.push(newData);

            this.inputSN = ''
          } else {
            this.$message.error('当前序列号不存在或已出库')
            this.inputSN = ''
            return
          }
        }
      }
    },
    tableDbEdit() {},
    async getSnCodeList() {
      //TODO 根据公司+仓库+物料去获取当前的在库序列号
      let params = {
        materialid: this.materialid,
        companyid: this.companyid,
        warehouseid: this.warehouseid
      }

      getAction(this.url.getinstocksnlist, params).then(res => {
        if (res) {
          if (res.success) {
            this.instocksnlist = res.result
          }
        }
      })
    },
    /**
     * 删除行
     */
    deletSubData() {
      if (!this.selectRowId) {
        this.$message.error('请选择要删除的行！')
        return
      }
      const afterDataSource = this.snDataSource.filter(item => item.id != this.selectRowId)
      if (afterDataSource) {
        this.snDataSource = afterDataSource
      }
    },
    onRowClick(row, event, column) {
      console.log('row' + JSON.stringify(row))
      this.selectRowId = row.id
    },
    async blurInput(id, name, value) {
      let obj = {}
      // 判断数据是否有所改变，如果数据有改变则调用修改接口
      // if(!value || value === ''){
      //   this.$message.error("序列号不能为空");
      //   return;
      // }
      if (this.oldData[name] != value) {
        obj[name] = value //被改变的数据
        // 然后再写调用接口，提交内容的东西就可以了
      }
      this.showInput = ''
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.snDataSource]
      const target = dataSource.find(item => item.key === key)
      if (target) {
        target[dataIndex] = value
        this.snDataSource = dataSource
      }
    },
    async newSubData() {
      // if(this.selectedRowKeys.length ==0){
      //   this.$message.error("请先选择对应物料行");
      //   return;
      // }
      // //判断当前行是否进行序列号管理
      // let currentSelectId= this.selectedRowKeys[0];

      // console.log("yyc"+currentSelectId);

      const newData = {
        id: randomUUID(),
        materialid: '',
        sncode: '',
        parentid: this.parentid
      }
      this.snDataSource = [...this.snDataSource, newData]
    },
    /**
     *
     *  显示当前物料的序列号
     * inventorytype 是入库 还是出库
     * parentid 当前行的主键id
     * materialid 当前行的物料id
     * qty 当前行的物料数量
     */
    show(inventorytype, parentid, materialid, qty, companyid, warehouseid) {
      this.inventorytype = inventorytype
      this.parentid = parentid
      this.materialid = materialid
      this.qty = qty
      this.visible = true
      this.companyid = companyid
      this.warehouseid = warehouseid

      let origDataSource = JSON.parse(localStorage.getItem(this.parentid))
      if (origDataSource) {
        this.snDataSource = origDataSource
      } else {
        //缓存没有，通过数据库去查询
        getAction(this.url.getsnlist, { parentid: this.parentid }).then(res => {
          if (res) {
            if (res.success) {
              this.snDataSource = res.result
            }
          } else {
            this.snDataSource = []
          }
        })
        // this.snDataSource = [];
      }
    },
    myHandleDetail(record) {
      // console.log('yyc:' + record)
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectDetailChange(selectedRowKeys) {
      this.selectedDetailRowKeys = selectedRowKeys
    },
    handleOk() {
      this.getSelectBillRows()
      if (this.snDataSource.length === 0) {
        this.$message.error('当前物料的序列号数量不能为0')
        return
      }
      if (this.snDataSource.length != this.qty) {
        this.$message.error('当前物料的序列号数量和物料数量不满足')
        return
      }
      localStorage.setItem(this.parentid, JSON.stringify(this.snDataSource))
      // if (this.selectedRowKeys) {
      //   this.$emit('ok', this.snDataSource);
      // }

      this.close()
    },
    onDateChange: function(value, dateString) {
      this.queryParam.beginTime = dateString[0].substring(0, 10)
      this.queryParam.endTime = dateString[1].substring(0, 10)
    },
    onDateOk(value) {
      console.log(value)
    },
    searchReset() {
      this.queryParam = {
        type: this.queryParam.type,
        subType: this.queryParam.subType,
        status: '1,3',
        vendorid: this.queryParam.vendorid
      }
      this.loadData(1)
    },
    getSelectBillRows() {
      let dataSource = this.dataSource
      this.selectBillRows = []
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRowKeys.includes(dataSource[i].id)) {
          this.selectBillRows.push(dataSource[i])
        }
      }
    },
    getSelectBillDetailRows() {
      let dataSource = this.dataSourceDetail
      this.selectBillDetailRows = []
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedDetailRowKeys.includes(dataSource[i].id)) {
          this.selectBillDetailRows.push(dataSource[i])
        }
      }
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
            this.handleOk()
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}
</style>
